package com.lsu.app.config;


import com.lsu.app.exception.RolePermissionException;
import com.lsu.app.tool.jwtUtil;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jws;
import io.jsonwebtoken.Jwts;

import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * @author hjj
 * @date 2023/10/17 18:12
 */
@Component
public class JwtRoleInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler){
        //获取token
        String token = request.getHeader("token");
        //如果不是映射到方法直接通过
        if(!(handler instanceof HandlerMethod)){
            return true;
        }
        // 解析JJWT令牌，获取用户角色信息

            //能解析成功(不出异常)，就说明token有效
            Jws<Claims> claimsJws = Jwts.parser().setSigningKey("financePlatform").parseClaimsJws(token);

        //获取信息
            Claims claims = claimsJws.getBody();
            Integer id = (Integer) claims.get("id");
            //检验是否为当前账号 token
            if(request.getSession().getAttribute("id")!=id){
                throw new RolePermissionException("用户已登出，无效令牌");
            }

            return true;

    }
}
